package com.shlh.saas.service.company.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shlh.saas.entity.company.EsGlobalEnterpriseFields;
import com.shlh.saas.entity.company.GlobalEnterpriseEs;
import com.shlh.saas.es.EsIndexInfo;
import com.shlh.saas.es.EsRestClient;
import com.shlh.saas.es.EsSearchRequest;
import com.shlh.saas.exception.BusinessException;
import com.shlh.saas.service.company.GlobalEnterpriseEsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@Slf4j
public class GlobalEnterpriseEsServiceImpl implements GlobalEnterpriseEsService {

    @Override
    public Page<GlobalEnterpriseEs> queryGlobalEnterpriseList(GlobalEnterpriseEs req) {
        Page<GlobalEnterpriseEs> pageResult = new Page<>();
        // 使用基础查询构建器
        BoolQueryBuilder bq = buildBaseQuery(req);

        // 设置分页参数
        long currentPage = Math.max(req.getCurrent(), 1);
        long pageSize = req.getSize() > 0 ? req.getSize() : 10;
        long from = (currentPage - 1) * pageSize;

        // 构建ES请求
        EsSearchRequest esSearchRequest = new EsSearchRequest();
        esSearchRequest.setBq(bq);
        esSearchRequest.setFields(EsGlobalEnterpriseFields.FIELD_QUERY);
        esSearchRequest.setFrom(from);
        esSearchRequest.setSize(pageSize);
        esSearchRequest.setNeedScroll(false);

        SearchResponse searchResponse =
                EsRestClient.searchWithTermQuery(getEsIndexInfo(), esSearchRequest);
        List<GlobalEnterpriseEs> globalEnterpriseEsList = new LinkedList<>();
        SearchHits searchHits = null;
        if (searchResponse != null) {
            searchHits = searchResponse.getHits();
        }
        if (searchHits == null || searchHits.getHits() == null) {
            pageResult.setTotal(0);
            pageResult.setSize(pageSize);
            pageResult.setRecords(globalEnterpriseEsList);
            return pageResult;
        }

        SearchHit[] hits = searchHits.getHits();
        log.debug("ES查询返回{}条结果", hits.length);

        for (SearchHit hit : hits) {
            GlobalEnterpriseEs globalEnterpriseEs = convertResult(hit);
            if (Objects.nonNull(globalEnterpriseEs)) {
                globalEnterpriseEsList.add(globalEnterpriseEs);
                log.debug("转换结果: {}", JSON.toJSON(globalEnterpriseEs));
            }
        }
        // 当前页码 - 使用计算后的值
        pageResult.setCurrent(currentPage);
        // 每页大小 - 使用计算后的值
        pageResult.setSize(pageSize);
        pageResult.setRecords(globalEnterpriseEsList);
        // 总记录数
        pageResult.setTotal(searchHits.getTotalHits().value);
        return pageResult;
    }

    @Override
    public long countGlobalEnterprise(GlobalEnterpriseEs globalEnterpriseEs) {
        try {
            log.info("🔍 开始ES计数查询: globalEnterpriseEs={}", JSON.toJSONString(globalEnterpriseEs));

            // 1. 构建计数请求
            EsSearchRequest esCountRequest = createEsCountRequest(globalEnterpriseEs);

            // 2. 执行计数查询
            SearchResponse searchResponse =
                    EsRestClient.searchWithTermQuery(getEsIndexInfo(), esCountRequest);

            // 3. 获取并返回精确计数
            long totalCount = searchResponse.getHits().getTotalHits().value;
            String relation = searchResponse.getHits().getTotalHits().relation.toString();

            log.info("🔍 ES计数查询结果: totalCount={}, relation={}, trackTotalHits生效={}",
                    totalCount, relation, esCountRequest.isTrackTotalHits());

            // 验证是否返回精确计数
            if (!"EQUAL_TO".equals(relation)) {
                log.warn("⚠️ ES返回的不是精确计数! relation={}, 可能trackTotalHits未生效", relation);
            }

            return totalCount;
        } catch (Exception e) {
            log.error("ES计数查询失败: globalEnterpriseEs={}, error={}",
                    JSON.toJSONString(globalEnterpriseEs), e.getMessage(), e);
            throw new BusinessException("ES计数操作失败", e);
        }
    }

    private EsSearchRequest createEsCountRequest(GlobalEnterpriseEs globalEnterpriseEs) {
        EsSearchRequest esSearchRequest = new EsSearchRequest();

        // 复用查询条件构建逻辑
        BoolQueryBuilder bq = buildBaseQuery(globalEnterpriseEs);

        // 计数请求特殊配置
        esSearchRequest.setBq(bq);
        esSearchRequest.setFields(null); // 计数不需要返回字段
        esSearchRequest.setFrom(0L);
        esSearchRequest.setSize(0L);      // size=0表示不返回文档
        esSearchRequest.setNeedScroll(false);
        esSearchRequest.setTrackTotalHits(true); // 确保返回精确计数

        log.info("🔍 ES计数查询配置: trackTotalHits={}, size={}, from={}",
                esSearchRequest.isTrackTotalHits(), esSearchRequest.getSize(), esSearchRequest.getFrom());
        log.debug("🔍 ES计数查询条件: {}", bq.toString());

        return esSearchRequest;
    }

    private BoolQueryBuilder buildBaseQuery(GlobalEnterpriseEs req) {
        BoolQueryBuilder bq = new BoolQueryBuilder();

        // 公司名称 - 使用精确匹配
        if (StringUtils.isNotBlank(req.getCompanyName())) {
            bq.filter(QueryBuilders.termQuery(EsGlobalEnterpriseFields.COMPANY_NAME + ".keyword",
                    req.getCompanyName().trim()));
        }

        // 联系人姓名 - 使用精确匹配
        if (StringUtils.isNotBlank(req.getFirstName())) {
            bq.filter(QueryBuilders.matchQuery(EsGlobalEnterpriseFields.FIRST_NAME,
                    req.getFirstName().trim()));
        }

        if (StringUtils.isNotBlank(req.getLastName())) {
            bq.filter(QueryBuilders.matchQuery(EsGlobalEnterpriseFields.LAST_NAME,
                    req.getLastName().trim()));
        }
        // 邮政编码 - 使用精确匹配
        if (StringUtils.isNotBlank(req.getCompanyZip())) {
            bq.filter(QueryBuilders.termQuery(EsGlobalEnterpriseFields.COMPANY_ZIP,
                    req.getCompanyZip().trim()));
        }
        // 公司所在州 - 使用精确匹配
        if (StringUtils.isNotBlank(req.getCompanyState())) {
            bq.filter(QueryBuilders.termQuery(EsGlobalEnterpriseFields.COMPANY_STATE,
                    req.getCompanyState().trim()));
        }

        // 城市 - 使用精确匹配
        if (StringUtils.isNotBlank(req.getCompanyCity())) {
            if (req.getCompanyCity().contains(",")) {
                String[] cityArr = req.getCompanyCity().split(",");
                BoolQueryBuilder cityBool = new BoolQueryBuilder();
                for (String city : cityArr) {
                    if (StringUtils.isNotBlank(city.trim())) {
                        cityBool.should(QueryBuilders.termQuery(
                                EsGlobalEnterpriseFields.COMPANY_CITY, city.trim()));
                    }
                }
                bq.filter(cityBool);
            } else {
                bq.filter(QueryBuilders.termQuery(
                        EsGlobalEnterpriseFields.COMPANY_CITY, req.getCompanyCity().trim()));
            }
        }

        // 行业 - 使用精确匹配
        if (StringUtils.isNotBlank(req.getCompanyIndustry())) {
            if (req.getCompanyIndustry().contains(",")) {
                String[] industryArr = req.getCompanyIndustry().split(",");
                BoolQueryBuilder industryBool = new BoolQueryBuilder();
                for (String industry : industryArr) {
                    if (StringUtils.isNotBlank(industry.trim())) {
                        industryBool.should(QueryBuilders.termQuery(
                                EsGlobalEnterpriseFields.COMPANY_INDUSTRY + ".keyword", industry.trim()));

                        industryBool.should(QueryBuilders.termQuery(
                                EsGlobalEnterpriseFields.PRIMARY_INDUSTRY + ".keyword", industry.trim()));
                    }
                }
                bq.filter(industryBool);
            } else {
                BoolQueryBuilder industryBool = new BoolQueryBuilder();
                industryBool.should(QueryBuilders.termQuery(
                        EsGlobalEnterpriseFields.COMPANY_INDUSTRY + ".keyword", req.getCompanyIndustry().trim()));
                industryBool.should(QueryBuilders.termQuery(
                        EsGlobalEnterpriseFields.PRIMARY_INDUSTRY + ".keyword", req.getCompanyIndustry().trim()));
                bq.filter(industryBool);
            }
        }

        // 员工规模 - 使用精确匹配
        if (StringUtils.isNotBlank(req.getEmployeeSizeCategory())) {
            if (req.getEmployeeSizeCategory().contains(",")) {
                String[] sizeArr = req.getEmployeeSizeCategory().split(",");
                BoolQueryBuilder sizeBool = new BoolQueryBuilder();
                for (String size : sizeArr) {
                    if (StringUtils.isNotBlank(size.trim())) {
                        sizeBool.should(QueryBuilders.termQuery(
                                EsGlobalEnterpriseFields.EMPLOYEE_SIZE_CATEGORY, size.trim()));
                    }
                }
                bq.filter(sizeBool);
            } else {
                bq.filter(QueryBuilders.termQuery(
                        EsGlobalEnterpriseFields.EMPLOYEE_SIZE_CATEGORY,
                        req.getEmployeeSizeCategory().trim()));
            }
        }

        // 收入规模 - 使用精确匹配
        if (StringUtils.isNotBlank(req.getRevenueSizeCategory())) {
            if (req.getRevenueSizeCategory().contains(",")) {
                String[] sizeArr = req.getRevenueSizeCategory().split(",");
                BoolQueryBuilder sizeBool = new BoolQueryBuilder();
                for (String size : sizeArr) {
                    if (StringUtils.isNotBlank(size.trim())) {
                        sizeBool.should(QueryBuilders.termQuery(
                                EsGlobalEnterpriseFields.REVENUE_SIZE_CATEGORY, size.trim()));
                    }
                }
                bq.filter(sizeBool);
            } else {
                bq.filter(QueryBuilders.termQuery(
                        EsGlobalEnterpriseFields.REVENUE_SIZE_CATEGORY,
                        req.getRevenueSizeCategory().trim()));
            }
        }

        // 部门 - 使用精确匹配
        if (StringUtils.isNotBlank(req.getDepartment())) {
            if (req.getDepartment().contains(",")) {
                String[] departmentArr = req.getDepartment().split(",");
                BoolQueryBuilder departmentBool = new BoolQueryBuilder();
                for (String department : departmentArr) {
                    if (StringUtils.isNotBlank(department.trim())) {
                        departmentBool.should(QueryBuilders.termQuery(
                                EsGlobalEnterpriseFields.COMPANY_DEPARTMENT + ".keyword", department.trim()));
                    }
                }
                bq.filter(departmentBool);
            } else {
                bq.filter(QueryBuilders.termQuery(
                        EsGlobalEnterpriseFields.COMPANY_DEPARTMENT + ".keyword",
                        req.getDepartment().trim()));
            }
        }

        // 职位 - 使用精确匹配
        if (StringUtils.isNotBlank(req.getJobTitle())) {
            if (req.getJobTitle().contains(",")) {
                String[] jobTitles = req.getJobTitle().split(",");
                BoolQueryBuilder jobTitleBool = new BoolQueryBuilder();
                for (String jobTitle : jobTitles) {
                    if (StringUtils.isNotBlank(jobTitle.trim())) {
                        jobTitleBool.should(QueryBuilders.termQuery(
                                EsGlobalEnterpriseFields.JOB_TITLE + ".keyword", jobTitle.trim()));
                    }
                }
                bq.filter(jobTitleBool);
            } else {
                bq.filter(QueryBuilders.termQuery(
                        EsGlobalEnterpriseFields.JOB_TITLE + ".keyword",
                        req.getJobTitle().trim()));
            }
        }

        if (StringUtils.isNotBlank(req.getCompanyPhone())) {
            bq.filter(QueryBuilders.termQuery(
                    EsGlobalEnterpriseFields.COMPANY_PHONE, req.getCompanyPhone().trim()));
        }

        if (StringUtils.isNotBlank(req.getBusinessEmail())) {
            bq.filter(QueryBuilders.termQuery(
                    EsGlobalEnterpriseFields.BUSINESS_EMAIL, req.getBusinessEmail().trim()));
        }

        if (StringUtils.isNotBlank(req.getMobilePhone())) {
            bq.filter(QueryBuilders.termQuery(
                    EsGlobalEnterpriseFields.MOBILE_PHONE, req.getMobilePhone().trim()));
        }

        if (StringUtils.isNotBlank(req.getCompanyDomain())) {
            bq.filter(QueryBuilders.wildcardQuery(
                    EsGlobalEnterpriseFields.COMPANY_DOMAIN,
                    "*" + req.getCompanyDomain().toLowerCase())
            );
        }

        if (StringUtils.isNotBlank(req.getHasContact())) {
            BoolQueryBuilder hasContact = QueryBuilders.boolQuery();

            if (req.getHasContact().contains("email")) {
                BoolQueryBuilder emailQuery = QueryBuilders.boolQuery()
                        .must(QueryBuilders.existsQuery(EsGlobalEnterpriseFields.BUSINESS_EMAIL))
                        .mustNot(QueryBuilders.termQuery(EsGlobalEnterpriseFields.BUSINESS_EMAIL, ""))
                        .must(QueryBuilders.wildcardQuery(EsGlobalEnterpriseFields.BUSINESS_EMAIL, "*@*"));
                hasContact.must(emailQuery);
            }
            if (req.getHasContact().contains("phone")) {
                BoolQueryBuilder phoneQuery = QueryBuilders.boolQuery()
                        .must(QueryBuilders.existsQuery(EsGlobalEnterpriseFields.COMPANY_PHONE))
                        .mustNot(QueryBuilders.termQuery(EsGlobalEnterpriseFields.COMPANY_PHONE, ""));
                hasContact.must(phoneQuery);
            }
            if (req.getHasContact().contains("mobile")) {
                BoolQueryBuilder mobileQuery = QueryBuilders.boolQuery()
                        .must(QueryBuilders.existsQuery(EsGlobalEnterpriseFields.MOBILE_PHONE))
                        .mustNot(QueryBuilders.termQuery(EsGlobalEnterpriseFields.MOBILE_PHONE, ""));
                hasContact.must(mobileQuery);
            }
            if (req.getHasContact().contains("website")) {
                BoolQueryBuilder websiteQuery = QueryBuilders.boolQuery()
                        .must(QueryBuilders.existsQuery(EsGlobalEnterpriseFields.COMPANY_LINKEDIN_URL))
                        .mustNot(QueryBuilders.termQuery(EsGlobalEnterpriseFields.COMPANY_LINKEDIN_URL, ""));
                hasContact.must(websiteQuery);
            }
            bq.filter(hasContact);
        }

        return bq;
    }

    /**
     * 从Map直接转换为GlobalEnterpriseEs对象（用于Scroll查询）
     */
    private GlobalEnterpriseEs convertResultFromMap(Map<String, Object> sourceAsMap) {
        if (CollectionUtils.isEmpty(sourceAsMap)) {
            return null;
        }

        GlobalEnterpriseEs globalEnterpriseEs = new GlobalEnterpriseEs();

        // 使用安全方法获取字段值
        globalEnterpriseEs.setId(getIntegerSafely(sourceAsMap, EsGlobalEnterpriseFields.MYSQL_ID));
        globalEnterpriseEs.setMysqlId(getStringSafely(sourceAsMap, EsGlobalEnterpriseFields.MYSQL_ID));
        globalEnterpriseEs.setMysqlTable(getStringSafely(sourceAsMap, EsGlobalEnterpriseFields.MYSQL_TABLE));
        globalEnterpriseEs.setCompanyName(getStringSafely(sourceAsMap, EsGlobalEnterpriseFields.COMPANY_NAME));
        globalEnterpriseEs.setCompanyPhone(getStringSafely(sourceAsMap, EsGlobalEnterpriseFields.COMPANY_PHONE));
        globalEnterpriseEs.setPrimaryIndustry(getStringSafely(sourceAsMap, EsGlobalEnterpriseFields.PRIMARY_INDUSTRY));
        globalEnterpriseEs.setCompanyZip(getStringSafely(sourceAsMap, EsGlobalEnterpriseFields.COMPANY_ZIP));
        globalEnterpriseEs.setCompanyRevenue(getStringSafely(sourceAsMap, EsGlobalEnterpriseFields.COMPANY_REVENUE));
        globalEnterpriseEs.setCompanyLinkedInUrl(getStringSafely(sourceAsMap, EsGlobalEnterpriseFields.COMPANY_LINKEDIN_URL));
        globalEnterpriseEs.setCompanyAddress(getStringSafely(sourceAsMap, EsGlobalEnterpriseFields.COMPANY_ADDRESS));
        globalEnterpriseEs.setCompanyIndustry(getStringSafely(sourceAsMap, EsGlobalEnterpriseFields.COMPANY_INDUSTRY));
        globalEnterpriseEs.setCompanyState(getStringSafely(sourceAsMap, EsGlobalEnterpriseFields.COMPANY_STATE));
        globalEnterpriseEs.setCompanyCity(getStringSafely(sourceAsMap, EsGlobalEnterpriseFields.COMPANY_CITY));
        globalEnterpriseEs.setBusinessEmail(getStringSafely(sourceAsMap, EsGlobalEnterpriseFields.BUSINESS_EMAIL));
        globalEnterpriseEs.setCompanyEmployeeCount(getStringSafely(sourceAsMap, EsGlobalEnterpriseFields.COMPANY_EMPLOYEE_COUNT));
        globalEnterpriseEs.setLastName(getStringSafely(sourceAsMap, EsGlobalEnterpriseFields.LAST_NAME));
        globalEnterpriseEs.setFirstName(getStringSafely(sourceAsMap, EsGlobalEnterpriseFields.FIRST_NAME));
        globalEnterpriseEs.setMobilePhone(getStringSafely(sourceAsMap, EsGlobalEnterpriseFields.MOBILE_PHONE));
        globalEnterpriseEs.setJobTitle(getStringSafely(sourceAsMap, EsGlobalEnterpriseFields.JOB_TITLE));
        globalEnterpriseEs.setDepartment(getStringSafely(sourceAsMap, EsGlobalEnterpriseFields.COMPANY_DEPARTMENT));
        globalEnterpriseEs.setCompanyDomain(getStringSafely(sourceAsMap, EsGlobalEnterpriseFields.COMPANY_DOMAIN));

        log.debug("成功转换Company ES记录: mysqlId={}, mysqlTable={}", globalEnterpriseEs.getMysqlId(), globalEnterpriseEs.getMysqlTable());

        return globalEnterpriseEs;
    }
    
    private GlobalEnterpriseEs convertResult(SearchHit hit) {
        Map<String, Object> sourceAsMap = hit.getSourceAsMap();
        return convertResultFromMap(sourceAsMap);
    }

    /**
     * 安全获取字符串值
     */
    private String getStringSafely(Map<String, Object> map, String key) {
        if (map == null || key == null) return null;
        Object value = map.get(key);
        return (value != null) ? value.toString() : null;
    }

    /**
     * 安全获取整数值
     */
    private Long getIntegerSafely(Map<String, Object> map, String key) {
        if (map == null || key == null) return null;
        Object value = map.get(key);
        if (value == null) return null;

        try {
            if (value instanceof Number) {
                return ((Number) value).longValue();
            }
            return Long.parseLong(value.toString());
        } catch (NumberFormatException e) {
            log.warn("无法转换为整数: key={}, value={}", key, value);
            return null;
        }
    }

    /**
     * 获取ES索引信息
     */
    private EsIndexInfo getEsIndexInfo() {
        EsIndexInfo esIndexInfo = new EsIndexInfo();
        esIndexInfo.setClusterName("my-es");
//        esIndexInfo.setClusterName("elasticsearch");
        esIndexInfo.setIndexName("global_companies");
        return esIndexInfo;
    }

    @Override
    public long countForExport(GlobalEnterpriseEs globalEnterpriseEs) {
        // 直接复用countGlobalEnterprise方法
        return countGlobalEnterprise(globalEnterpriseEs);
    }

    @Override
    public List<GlobalEnterpriseEs> searchGlobalEnterpriseByEmail(String searchKeyword, int offset, int size) {
        log.info("开始GlobalEnterpriseES查询: searchKeyword={}, offset={}, size={}", searchKeyword, offset, size);
        GlobalEnterpriseEs globalEnterpriseEs = new GlobalEnterpriseEs();
        globalEnterpriseEs.setFirstName(searchKeyword);
        globalEnterpriseEs.setLastName(searchKeyword);
        globalEnterpriseEs.setCompanyName(searchKeyword);
        globalEnterpriseEs.setCompanyLinkedInUrl(searchKeyword);
        globalEnterpriseEs.setBusinessEmail("email");

        // 使用基础查询构建器
        BoolQueryBuilder bq = buildWithEmailAndPhoneQuery(globalEnterpriseEs);

        // 设置分页参数
        long pageSize = size > 0 ? size : 10;

        // 构建ES请求
        EsSearchRequest esSearchRequest = new EsSearchRequest();
        esSearchRequest.setBq(bq);
        esSearchRequest.setFields(EsGlobalEnterpriseFields.FIELD_QUERY);
        esSearchRequest.setFrom((long) offset);
        esSearchRequest.setSize(pageSize);
        esSearchRequest.setNeedScroll(false);

        SearchResponse searchResponse =
                EsRestClient.searchWithTermQuery(getEsIndexInfo(), esSearchRequest);
        List<GlobalEnterpriseEs> globalEnterpriseEsList = new LinkedList<>();
        SearchHits searchHits = null;
        if (searchResponse != null) {
            searchHits = searchResponse.getHits();
        }
        if (searchHits == null || searchHits.getHits() == null) {
            return globalEnterpriseEsList;
        }

        SearchHit[] hits = searchHits.getHits();
        log.debug("GlobalEnterpriseES查询返回{}条结果", hits.length);

        for (SearchHit hit : hits) {
            GlobalEnterpriseEs globalEnterpriseEs1 = convertResult(hit);
            if (Objects.nonNull(globalEnterpriseEs1)) {
                globalEnterpriseEsList.add(globalEnterpriseEs1);
            }
        }

        return globalEnterpriseEsList;

    }

    private BoolQueryBuilder buildWithEmailAndPhoneQuery(GlobalEnterpriseEs req) {

        BoolQueryBuilder bq = new BoolQueryBuilder();

        // 创建一个内部布尔查询用于处理邮箱或电话的必须条件
        BoolQueryBuilder contactMustQuery = QueryBuilders.boolQuery();

        // 处理邮箱条件
        if (StringUtils.isNotBlank(req.getBusinessEmail())) {
            // 邮箱必须存在且不为空，并且匹配传入的值
            contactMustQuery.should(QueryBuilders.boolQuery()
                    .must(QueryBuilders.existsQuery(EsGlobalEnterpriseFields.BUSINESS_EMAIL))
                    .mustNot(QueryBuilders.termQuery(EsGlobalEnterpriseFields.BUSINESS_EMAIL, ""))
                    .must(QueryBuilders.termQuery(EsGlobalEnterpriseFields.BUSINESS_EMAIL + ".keyword",
                            req.getBusinessEmail().trim())));
        }

        // 处理电话条件
        if (StringUtils.isNotBlank(req.getMobilePhone())) {
            // 电话必须存在且不为空，并且匹配传入的值
            contactMustQuery.should(QueryBuilders.boolQuery()
                    .must(QueryBuilders.existsQuery(EsGlobalEnterpriseFields.MOBILE_PHONE))
                    .mustNot(QueryBuilders.termQuery(EsGlobalEnterpriseFields.MOBILE_PHONE, ""))
                    .mustNot(QueryBuilders.termQuery(EsGlobalEnterpriseFields.MOBILE_PHONE, "/N"))
                    .must(QueryBuilders.termQuery(EsGlobalEnterpriseFields.MOBILE_PHONE + ".keyword",
                            req.getMobilePhone().trim())));
        }

        // 将邮箱或电话条件作为必须条件
        // 注意：如果既没有邮箱也没有电话，这个条件会为空，可能需要额外处理
        if (!contactMustQuery.should().isEmpty()) {
            bq.must(contactMustQuery);
        }

        // 其他字段作为可选条件（OR关系）
        BoolQueryBuilder optionalFieldsQuery = QueryBuilders.boolQuery();

        // 公司名称 - 使用精确匹配
        if (StringUtils.isNotBlank(req.getCompanyName())) {
            optionalFieldsQuery.should(QueryBuilders.termQuery(
                    EsGlobalEnterpriseFields.COMPANY_NAME + ".keyword",
                    req.getCompanyName().trim()));
        }

        // 联系人姓名 - 使用精确匹配
        if (StringUtils.isNotBlank(req.getFirstName())) {
            optionalFieldsQuery.should(QueryBuilders.termQuery(
                    EsGlobalEnterpriseFields.FIRST_NAME,
                    req.getFirstName().trim()));
        }

        if (StringUtils.isNotBlank(req.getLastName())) {
            optionalFieldsQuery.should(QueryBuilders.termQuery(
                    EsGlobalEnterpriseFields.LAST_NAME,
                    req.getLastName().trim()));
        }

        // 公司网址
        if (StringUtils.isNotBlank(req.getCompanyLinkedInUrl())) {
            optionalFieldsQuery.should(QueryBuilders.termQuery(
                    EsGlobalEnterpriseFields.COMPANY_LINKEDIN_URL,
                    req.getCompanyLinkedInUrl().trim()));
        }

        // 如果有可选字段条件，添加到主查询中
        if (!optionalFieldsQuery.should().isEmpty()) {
            bq.must(optionalFieldsQuery);
        }

        return bq;

    }

    @Override
    public Long countGlobalEnterpriseByEmail(String searchKeyword) {
        log.info("开始GlobalEnterpriseES计数: searchKeyword={}", searchKeyword);
        GlobalEnterpriseEs globalEnterpriseEs = new GlobalEnterpriseEs();
        globalEnterpriseEs.setFirstName(searchKeyword);
        globalEnterpriseEs.setLastName(searchKeyword);
        globalEnterpriseEs.setCompanyName(searchKeyword);
        globalEnterpriseEs.setCompanyLinkedInUrl(searchKeyword);
        globalEnterpriseEs.setBusinessEmail("email");

        // 使用基础查询构建器
        BoolQueryBuilder bq = buildWithEmailAndPhoneQuery(globalEnterpriseEs);

        // 构建ES请求
        EsSearchRequest esSearchRequest = new EsSearchRequest();
        esSearchRequest.setBq(bq);
        esSearchRequest.setFields(null); // 计数不需要返回字段
        esSearchRequest.setFrom(0L);
        esSearchRequest.setSize(0L);      // size=0表示不返回文档
        esSearchRequest.setNeedScroll(false);
        esSearchRequest.setTrackTotalHits(true); // 确保返回精确计数

        SearchResponse searchResponse =
                EsRestClient.searchWithTermQuery(getEsIndexInfo(), esSearchRequest);
        if (searchResponse == null) {
            return 0L;
        }

        long totalCount = Objects.requireNonNull(searchResponse.getHits().getTotalHits()).value;
        log.info("GlobalEnterpriseES计数返回{}条结果", totalCount);

        return totalCount;
    }

    @Override
    public List<GlobalEnterpriseEs> searchCompaniesWithPhone(String searchKeyword, int offset, int size) {
        log.info("开始GlobalEnterpriseES查询: searchKeyword={}, offset={}, size={}", searchKeyword, offset, size);
        GlobalEnterpriseEs globalEnterpriseEs = new GlobalEnterpriseEs();
        globalEnterpriseEs.setMobilePhone("phone");
        globalEnterpriseEs.setFirstName(searchKeyword);
        globalEnterpriseEs.setLastName(searchKeyword);
        globalEnterpriseEs.setCompanyName(searchKeyword);
        globalEnterpriseEs.setCompanyLinkedInUrl(searchKeyword);

        // 使用基础查询构建器
        BoolQueryBuilder bq = buildWithEmailAndPhoneQuery(globalEnterpriseEs);

        // 设置分页参数
        long pageSize = size > 0 ? size : 10;

        // 构建ES请求
        EsSearchRequest esSearchRequest = new EsSearchRequest();
        esSearchRequest.setBq(bq);
        esSearchRequest.setFields(EsGlobalEnterpriseFields.FIELD_QUERY);
        esSearchRequest.setFrom((long) offset);
        esSearchRequest.setSize(pageSize);
        esSearchRequest.setNeedScroll(false);

        SearchResponse searchResponse =
                EsRestClient.searchWithTermQuery(getEsIndexInfo(), esSearchRequest);
        List<GlobalEnterpriseEs> globalEnterpriseEsList = new LinkedList<>();
        SearchHits searchHits = null;
        if (searchResponse != null) {
            searchHits = searchResponse.getHits();
        }
        if (searchHits == null || searchHits.getHits() == null) {
            return globalEnterpriseEsList;
        }
        SearchHit[] hits = searchHits.getHits();
        log.debug("GlobalEnterpriseES查询返回{}条结果", hits.length);

        for (SearchHit hit : hits) {
            GlobalEnterpriseEs globalEnterpriseEs1 = convertResult(hit);
            if (Objects.nonNull(globalEnterpriseEs1)) {
                globalEnterpriseEsList.add(globalEnterpriseEs1);
            }
        }

        return globalEnterpriseEsList;

    }

    @Override
    public Long countCompaniesWithPhone(String searchKeyword) {
        log.info("开始GlobalEnterpriseES计数: searchKeyword={}", searchKeyword);
        GlobalEnterpriseEs globalEnterpriseEs = new GlobalEnterpriseEs();
        globalEnterpriseEs.setMobilePhone("phone");
        globalEnterpriseEs.setFirstName(searchKeyword);
        globalEnterpriseEs.setLastName(searchKeyword);
        globalEnterpriseEs.setCompanyName(searchKeyword);
        globalEnterpriseEs.setCompanyLinkedInUrl(searchKeyword);

        // 使用基础查询构建器
        BoolQueryBuilder bq = buildWithEmailAndPhoneQuery(globalEnterpriseEs);

        // 构建ES请求
        EsSearchRequest esSearchRequest = new EsSearchRequest();
        esSearchRequest.setBq(bq);
        esSearchRequest.setFields(null); // 计数不需要返回字段
        esSearchRequest.setFrom(0L);
        esSearchRequest.setSize(0L);      // size=0表示不返回文档
        esSearchRequest.setNeedScroll(false);
        esSearchRequest.setTrackTotalHits(true); // 确保返回精确计数

        SearchResponse searchResponse =
                EsRestClient.searchWithTermQuery(getEsIndexInfo(), esSearchRequest);
        if (searchResponse == null) {
            return 0L;
        }

        long totalCount = Objects.requireNonNull(searchResponse.getHits().getTotalHits()).value;
        log.info("GlobalEnterpriseES计数返回{}条结果", totalCount);

        return totalCount;
    }

    @Override
    public List<Map<String, String>> searchGlobalEnterpriseWithEmail(String email, int limit) {
        log.info("ES两阶段查询 - 邮箱: email:{}", email);
        try {
            BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

            // 邮箱精确匹配（必须条件）
            if (email != null && !email.trim().isEmpty()) {
                boolQuery.must(QueryBuilders.termQuery(EsGlobalEnterpriseFields.BUSINESS_EMAIL, email.toLowerCase()));
            }

            return executeEsSearchForIdentifiers(boolQuery, 0, Math.min(limit, 50));

        } catch (Exception e) {
            log.error("ES查询失败 - 邮箱精确匹配: email={}, error={}", email, e.getMessage(), e);
            return new ArrayList<>();
        }

    }

    @Override
    public List<Map<String, String>> searchGlobalEnterpriseWithPhone(String phone, int limit) {
        log.info("ES两阶段查询 - 电话号码: phone:{}", phone);
        try {
            BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

            // 电话号码精确匹配（必须条件）
            if (phone != null && !phone.trim().isEmpty()) {
                boolQuery.should(QueryBuilders.termQuery(EsGlobalEnterpriseFields.COMPANY_PHONE, phone));
                boolQuery.should(QueryBuilders.termQuery(EsGlobalEnterpriseFields.MOBILE_PHONE, phone));
            }

            return executeEsSearchForIdentifiers(boolQuery, 0, Math.min(limit, 50));

        } catch (Exception e) {
            log.error("ES查询失败 - 电话号码精确匹配: phone={}, error={}", phone, e.getMessage(), e);
            return new ArrayList<>();
        }

    }

    @Override
    public List<Map<String, String>> findGlobalEnterpriseByEmail(String value, int offset, int size) {
        GlobalEnterpriseEs globalEnterpriseEs = new GlobalEnterpriseEs();
        globalEnterpriseEs.setBusinessEmail(value);

        return findGlobalEnterprise(globalEnterpriseEs, offset, size);

    }

    @Override
    public List<Map<String, String>> findGlobalEnterpriseByPhone(String value, int offset, int size) {
        GlobalEnterpriseEs globalEnterpriseEs = new GlobalEnterpriseEs();
        globalEnterpriseEs.setCompanyPhone(value);

        return findGlobalEnterprise(globalEnterpriseEs, offset, size);
    }

    @Override
    public List<Map<String, String>> findGlobalEnterpriseByDomain(String domain, int size, int offset) {
        GlobalEnterpriseEs globalEnterpriseEs = new GlobalEnterpriseEs();
        globalEnterpriseEs.setCompanyDomain(domain);

        return findGlobalEnterprise(globalEnterpriseEs, offset, size);
    }

    @Override
    public List<String> searchCities(String city) {
        // 使用Set自动去重
        Set<String> uniqueCities = new HashSet<>();

        BoolQueryBuilder bq = new BoolQueryBuilder();
        bq.should(QueryBuilders.wildcardQuery(EsGlobalEnterpriseFields.COMPANY_CITY, city + "*"));
        bq.should(QueryBuilders.matchQuery(EsGlobalEnterpriseFields.COMPANY_CITY, city).fuzziness("AUTO"));
// 执行搜索并获取城市列表
        List<Map<String, Object>> results = executeEsSearchForCity(bq, city);
// 提取并去重城市名称
        for (Map<String, Object> result : results) {
            Object cityObj = result.get(EsGlobalEnterpriseFields.COMPANY_CITY);
            if (cityObj != null) {
                if (cityObj instanceof String) {
                    uniqueCities.add((String) cityObj);
                } else if (cityObj instanceof List) {
                    for (Object item : (List<?>) cityObj) {
                        if (item instanceof String) {
                            uniqueCities.add((String) item);
                        }
                    }
                }
            }
        }

        // 转换为列表并返回
        return new ArrayList<>(uniqueCities);

    }

    @Override
    public List<String> searchIndustries(String industry) {
        // 使用Set自动去重
        Set<String> uniqueCities = new HashSet<>();

        BoolQueryBuilder bq = new BoolQueryBuilder();
        bq.should(QueryBuilders.wildcardQuery(EsGlobalEnterpriseFields.COMPANY_INDUSTRY, industry + "*"));
        bq.should(QueryBuilders.matchQuery(EsGlobalEnterpriseFields.COMPANY_INDUSTRY, industry).fuzziness("AUTO"));
// 执行搜索并获取城市列表
        List<Map<String, Object>> results = executeEsSearchForIndustry(bq, industry);
// 提取并去重城市名称
        for (Map<String, Object> result : results) {
            Object cityObj = result.get(EsGlobalEnterpriseFields.COMPANY_INDUSTRY);
            if (cityObj != null) {
                if (cityObj instanceof String) {
                    uniqueCities.add((String) cityObj);
                } else if (cityObj instanceof List) {
                    for (Object item : (List<?>) cityObj) {
                        if (item instanceof String) {
                            uniqueCities.add((String) item);
                        }
                    }
                }
            }
        }

        // 转换为列表并返回
        return new ArrayList<>(uniqueCities);

    }

    @Override
    public List<String> searchOccupations(String occupations) {
        // 使用Set自动去重
        Set<String> uniqueCities = new HashSet<>();

        BoolQueryBuilder bq = new BoolQueryBuilder();
        bq.should(QueryBuilders.wildcardQuery(EsGlobalEnterpriseFields.JOB_TITLE, occupations + "*"));
        bq.should(QueryBuilders.matchQuery(EsGlobalEnterpriseFields.JOB_TITLE, occupations).fuzziness("AUTO"));
// 执行搜索并获取城市列表
        List<Map<String, Object>> results = executeEsSearchForOccupation(bq, occupations);
// 提取并去重城市名称
        for (Map<String, Object> result : results) {
            Object cityObj = result.get(EsGlobalEnterpriseFields.JOB_TITLE);
            if (cityObj != null) {
                if (cityObj instanceof String) {
                    uniqueCities.add((String) cityObj);
                } else if (cityObj instanceof List) {
                    for (Object item : (List<?>) cityObj) {
                        if (item instanceof String) {
                            uniqueCities.add((String) item);
                        }
                    }
                }
            }
        }

        // 转换为列表并返回
        return new ArrayList<>(uniqueCities);

    }

    @Override
    public List<String> searchDepartments(String departments) {
        // 使用Set自动去重
        Set<String> uniqueCities = new HashSet<>();

        BoolQueryBuilder bq = new BoolQueryBuilder();
        bq.should(QueryBuilders.wildcardQuery(EsGlobalEnterpriseFields.COMPANY_DEPARTMENT, departments + "*"));
        bq.should(QueryBuilders.matchQuery(EsGlobalEnterpriseFields.COMPANY_DEPARTMENT, departments).fuzziness("AUTO"));
// 执行搜索并获取城市列表
        List<Map<String, Object>> results = executeEsSearchForDepartment(bq, departments);
// 提取并去重城市名称
        for (Map<String, Object> result : results) {
            Object cityObj = result.get(EsGlobalEnterpriseFields.COMPANY_DEPARTMENT);
            if (cityObj != null) {
                if (cityObj instanceof String) {
                    uniqueCities.add((String) cityObj);
                } else if (cityObj instanceof List) {
                    for (Object item : (List<?>) cityObj) {
                        if (item instanceof String) {
                            uniqueCities.add((String) item);
                        }
                    }
                }
            }
        }

        // 转换为列表并返回
        return new ArrayList<>(uniqueCities);

    }

    @Override
    public List<GlobalEnterpriseEs> searchCompanyDataByPhone(String companyName, String fullName, String website) {

        GlobalEnterpriseEs globalEnterpriseEs = new GlobalEnterpriseEs();
        globalEnterpriseEs.setCompanyName(companyName);
        globalEnterpriseEs.setFirstName(fullName);
        globalEnterpriseEs.setCompanyLinkedInUrl(website);
        globalEnterpriseEs.setHasContact("phone");

        // 使用基础查询构建器
        BoolQueryBuilder bq = searchCompanyDataWithPhoneEmailQuery(globalEnterpriseEs);

        EsSearchRequest esSearchRequest = new EsSearchRequest();
        esSearchRequest.setBq(bq);
        esSearchRequest.setFields(EsGlobalEnterpriseFields.FIELD_QUERY);
        // 使用普通分页查询，限制最多返回5000条，避免查询过多数据
        esSearchRequest.setNeedScroll(false); // 不使用Scroll，使用普通查询
        esSearchRequest.setFrom(0L); // 设置起始位置
        esSearchRequest.setSize(5000L); // 最多返回5000条记录

        log.info("执行GlobalEnterprise ES查询，限制最多返回5000条结果");

        // 2. 执行查询
        // 使用普通查询而非scroll查询
        SearchResponse searchResponse = EsRestClient.searchWithTermQuery(getEsIndexInfo(), esSearchRequest);

        List<GlobalEnterpriseEs> globalEnterpriseEsList = new LinkedList<>();
        if (searchResponse != null && searchResponse.getHits() != null) {
            SearchHits hits = searchResponse.getHits();
            log.info("LinkedIn ES查询完成，共找到{}条匹配数据", hits.getTotalHits().value);

            for (SearchHit hit : hits.getHits()) {
                GlobalEnterpriseEs user = convertResultFromMap(hit.getSourceAsMap());
                if (user != null) {
                    globalEnterpriseEsList.add(user);
                }
            }
        }

        return globalEnterpriseEsList;

    }

    @Override
    public List<GlobalEnterpriseEs> searchCompanyDataByEmail(String companyName, String fullName, String website) {
        GlobalEnterpriseEs globalEnterpriseEs = new GlobalEnterpriseEs();
        globalEnterpriseEs.setCompanyName(companyName);
        globalEnterpriseEs.setFirstName(fullName);
        globalEnterpriseEs.setCompanyLinkedInUrl(website);
        globalEnterpriseEs.setHasContact("email");

        // 使用基础查询构建器
        BoolQueryBuilder bq = searchCompanyDataWithPhoneEmailQuery(globalEnterpriseEs);

        EsSearchRequest esSearchRequest = new EsSearchRequest();
        esSearchRequest.setBq(bq);
        esSearchRequest.setFields(EsGlobalEnterpriseFields.FIELD_QUERY);
        // 使用普通分页查询，限制最多返回5000条，避免查询过多数据
        esSearchRequest.setNeedScroll(false); // 不使用Scroll，使用普通查询
        esSearchRequest.setFrom(0L); // 设置起始位置
        esSearchRequest.setSize(5000L); // 最多返回5000条记录

        log.info("执行GlobalEnterprise ES查询，限制最多返回5000条结果");

        // 2. 执行查询
        // 使用普通查询而非scroll查询
        SearchResponse searchResponse = EsRestClient.searchWithTermQuery(getEsIndexInfo(), esSearchRequest);

        List<GlobalEnterpriseEs> globalEnterpriseEsList = new LinkedList<>();
        if (searchResponse != null && searchResponse.getHits() != null) {
            SearchHits hits = searchResponse.getHits();
            log.info("LinkedIn ES查询完成，共找到{}条匹配数据", hits.getTotalHits().value);

            for (SearchHit hit : hits.getHits()) {
                GlobalEnterpriseEs user = convertResultFromMap(hit.getSourceAsMap());
                if (user != null) {
                    globalEnterpriseEsList.add(user);
                }
            }
        }

        return globalEnterpriseEsList;
    }


    private BoolQueryBuilder searchCompanyDataWithPhoneEmailQuery(GlobalEnterpriseEs globalEnterpriseEs) {
        BoolQueryBuilder bq = QueryBuilders.boolQuery();

        // 公司名称查询
        if (StringUtils.isNotBlank(globalEnterpriseEs.getCompanyName())) {
            String companyName = globalEnterpriseEs.getCompanyName();
            bq.must(QueryBuilders.termQuery(EsGlobalEnterpriseFields.COMPANY_NAME + ".keyword", companyName));
        }

        // 姓名查询（支持全名分割）
        if (StringUtils.isNotBlank(globalEnterpriseEs.getFirstName())) {
            String fullName = globalEnterpriseEs.getFirstName().trim();

            if (fullName.contains(" ")) {
                String[] names = fullName.split("\\s+");
                if (names.length >= 2) {
                    // 取第一个词作为名
                    bq.must(QueryBuilders.matchQuery(EsGlobalEnterpriseFields.FIRST_NAME, names[0]));
                    // 取最后一个词作为姓
                    bq.must(QueryBuilders.matchQuery(EsGlobalEnterpriseFields.LAST_NAME, names[names.length-1]));
                } else {
                    // 单个词的情况（虽然理论上不会发生）
                    buildNameQuery(bq, fullName);
                }
            } else {
                // 没有空格的情况
                buildNameQuery(bq, fullName);
            }
        }

        // LinkedIn URL查询
        if (StringUtils.isNotBlank(globalEnterpriseEs.getCompanyLinkedInUrl())) {
            String linkedInUrl = globalEnterpriseEs.getCompanyLinkedInUrl().trim();
            // 使用termQuery确保精确匹配
            bq.must(QueryBuilders.termQuery(EsGlobalEnterpriseFields.COMPANY_LINKEDIN_URL, linkedInUrl));
        }

        // 联系方式查询
        if (StringUtils.isNotBlank(globalEnterpriseEs.getHasContact())) {
            String contactType = globalEnterpriseEs.getHasContact().trim().toLowerCase();

            if ("phone".equals(contactType)) {
                // 创建手机号或公司电话存在的条件
                BoolQueryBuilder phoneExistsQuery = QueryBuilders.boolQuery();

                // mobile_phone 存在的条件
                BoolQueryBuilder mobilePhoneQuery = QueryBuilders.boolQuery();
                mobilePhoneQuery.must(QueryBuilders.existsQuery(EsGlobalEnterpriseFields.MOBILE_PHONE));
                mobilePhoneQuery.mustNot(QueryBuilders.termQuery(EsGlobalEnterpriseFields.MOBILE_PHONE, ""));
                mobilePhoneQuery.mustNot(QueryBuilders.termQuery(EsGlobalEnterpriseFields.MOBILE_PHONE, "/N"));

                // company_phone 存在的条件
                BoolQueryBuilder companyPhoneQuery = QueryBuilders.boolQuery();
                companyPhoneQuery.must(QueryBuilders.existsQuery(EsGlobalEnterpriseFields.COMPANY_PHONE));
                companyPhoneQuery.mustNot(QueryBuilders.termQuery(EsGlobalEnterpriseFields.COMPANY_PHONE, ""));
                companyPhoneQuery.mustNot(QueryBuilders.termQuery(EsGlobalEnterpriseFields.COMPANY_PHONE, "/N"));

                // 使用 should 表示两者满足一个即可
                phoneExistsQuery.should(mobilePhoneQuery);
                phoneExistsQuery.should(companyPhoneQuery);
                phoneExistsQuery.minimumShouldMatch(1); // 至少满足一个条件

                bq.must(phoneExistsQuery);

            } else if ("email".equals(contactType)) {
                // 邮箱存在且不为空
                bq.must(QueryBuilders.existsQuery(EsGlobalEnterpriseFields.BUSINESS_EMAIL));
                bq.must(QueryBuilders.boolQuery()
                        .mustNot(QueryBuilders.termQuery(EsGlobalEnterpriseFields.BUSINESS_EMAIL, ""))
                        .mustNot(QueryBuilders.termQuery(EsGlobalEnterpriseFields.BUSINESS_EMAIL, "/N")));
            } else {
                log.warn("未知的联系方式类型: {}", contactType);
            }
        }

        log.info("bq:{}", bq);
        return bq;
    }

    // 辅助方法：构建姓名查询
    private void buildNameQuery(BoolQueryBuilder bq, String name) {
        BoolQueryBuilder nameQuery = QueryBuilders.boolQuery()
                .should(QueryBuilders.matchQuery(EsGlobalEnterpriseFields.FIRST_NAME, name))
                .should(QueryBuilders.matchQuery(EsGlobalEnterpriseFields.LAST_NAME, name))
                .minimumShouldMatch(1);
        bq.must(nameQuery);
    }

    private List<Map<String, Object>> executeEsSearchForDepartment(BoolQueryBuilder boolQuery, String departments) {
        List<Map<String, Object>> results = new ArrayList<>();
        final int MAX_RESULTS = 20; // 限制最大结果数

        try {
            // 创建ES搜索请求
            EsSearchRequest esSearchRequest = new EsSearchRequest();
            esSearchRequest.setBq(boolQuery);
            esSearchRequest.setFrom(0L);
            esSearchRequest.setSize((long) MAX_RESULTS);
            esSearchRequest.setNeedScroll(false);

            // 只查询行业字段
            String[] fields = {EsGlobalEnterpriseFields.COMPANY_DEPARTMENT};
            esSearchRequest.setFields(fields);

            // 执行查询
            SearchResponse searchResponse = EsRestClient.searchWithTermQuery(getEsIndexInfo(), esSearchRequest);

            if (searchResponse == null) {
                log.warn("ES查询返回null响应");
                return results;
            }

            SearchHits searchHits = searchResponse.getHits();
            if (searchHits == null || searchHits.getHits() == null) {
                log.warn("ES查询返回空结果");
                return results;
            }

            SearchHit[] hits = searchHits.getHits();
            log.info("ES查询返回{}条匹配记录", hits.length);

            // 提取城市信息
            for (SearchHit hit : hits) {
                Map<String, Object> sourceAsMap = hit.getSourceAsMap();
                if (sourceAsMap != null && sourceAsMap.containsKey(EsGlobalEnterpriseFields.COMPANY_DEPARTMENT)) {
                    results.add(sourceAsMap);
                }
            }

            log.info("ES查询完成，有效匹配记录数: {}", results.size());
            return results;

        } catch (Exception e) {
            log.error("执行ES查询失败: {}", e.getMessage(), e);
            return results;
        }
    }

    private List<Map<String, Object>> executeEsSearchForOccupation(BoolQueryBuilder boolQuery, String occupations) {
        List<Map<String, Object>> results = new ArrayList<>();
        final int MAX_RESULTS = 20; // 限制最大结果数

        try {
            // 创建ES搜索请求
            EsSearchRequest esSearchRequest = new EsSearchRequest();
            esSearchRequest.setBq(boolQuery);
            esSearchRequest.setFrom(0L);
            esSearchRequest.setSize((long) MAX_RESULTS);
            esSearchRequest.setNeedScroll(false);

            // 只查询行业字段
            String[] fields = {EsGlobalEnterpriseFields.JOB_TITLE};
            esSearchRequest.setFields(fields);

            // 执行查询
            SearchResponse searchResponse = EsRestClient.searchWithTermQuery(getEsIndexInfo(), esSearchRequest);

            if (searchResponse == null) {
                log.warn("ES查询返回null响应");
                return results;
            }

            SearchHits searchHits = searchResponse.getHits();
            if (searchHits == null || searchHits.getHits() == null) {
                log.warn("ES查询返回空结果");
                return results;
            }

            SearchHit[] hits = searchHits.getHits();
            log.info("ES查询返回{}条匹配记录", hits.length);

            // 提取城市信息
            for (SearchHit hit : hits) {
                Map<String, Object> sourceAsMap = hit.getSourceAsMap();
                if (sourceAsMap != null && sourceAsMap.containsKey(EsGlobalEnterpriseFields.JOB_TITLE)) {
                    results.add(sourceAsMap);
                }
            }

            log.info("ES查询完成，有效匹配记录数: {}", results.size());
            return results;

        } catch (Exception e) {
            log.error("执行ES查询失败: {}", e.getMessage(), e);
            return results;
        }
    }

    private List<Map<String, Object>> executeEsSearchForIndustry(BoolQueryBuilder boolQuery, String industry) {
        List<Map<String, Object>> results = new ArrayList<>();
        final int MAX_RESULTS = 20; // 限制最大结果数

        try {
            // 创建ES搜索请求
            EsSearchRequest esSearchRequest = new EsSearchRequest();
            esSearchRequest.setBq(boolQuery);
            esSearchRequest.setFrom(0L);
            esSearchRequest.setSize((long) MAX_RESULTS);
            esSearchRequest.setNeedScroll(false);

            // 只查询行业字段
            String[] fields = {EsGlobalEnterpriseFields.COMPANY_INDUSTRY};
            esSearchRequest.setFields(fields);

            // 执行查询
            SearchResponse searchResponse = EsRestClient.searchWithTermQuery(getEsIndexInfo(), esSearchRequest);

            if (searchResponse == null) {
                log.warn("ES查询返回null响应");
                return results;
            }

            SearchHits searchHits = searchResponse.getHits();
            if (searchHits == null || searchHits.getHits() == null) {
                log.warn("ES查询返回空结果");
                return results;
            }

            SearchHit[] hits = searchHits.getHits();
            log.info("ES查询返回{}条匹配记录", hits.length);

            // 提取城市信息
            for (SearchHit hit : hits) {
                Map<String, Object> sourceAsMap = hit.getSourceAsMap();
                if (sourceAsMap != null && sourceAsMap.containsKey(EsGlobalEnterpriseFields.COMPANY_INDUSTRY)) {
                    results.add(sourceAsMap);
                }
            }

            log.info("ES查询完成，有效匹配记录数: {}", results.size());
            return results;

        } catch (Exception e) {
            log.error("执行ES查询失败: {}", e.getMessage(), e);
            return results;
        }
    }

    private List<Map<String, Object>> executeEsSearchForCity(BoolQueryBuilder boolQuery, String city) {
        List<Map<String, Object>> results = new ArrayList<>();
        final int MAX_RESULTS = 20; // 限制最大结果数

        try {
            // 创建ES搜索请求
            EsSearchRequest esSearchRequest = new EsSearchRequest();
            esSearchRequest.setBq(boolQuery);
            esSearchRequest.setFrom(0L);
            esSearchRequest.setSize((long) MAX_RESULTS);
            esSearchRequest.setNeedScroll(false);

            // 只查询城市字段
            String[] fields = {EsGlobalEnterpriseFields.COMPANY_CITY};
            esSearchRequest.setFields(fields);

            // 执行查询
            SearchResponse searchResponse = EsRestClient.searchWithTermQuery(getEsIndexInfo(), esSearchRequest);

            if (searchResponse == null) {
                log.warn("ES查询返回null响应");
                return results;
            }

            SearchHits searchHits = searchResponse.getHits();
            if (searchHits == null || searchHits.getHits() == null) {
                log.warn("ES查询返回空结果");
                return results;
            }

            SearchHit[] hits = searchHits.getHits();
            log.info("ES查询返回{}条匹配记录", hits.length);

            // 提取城市信息
            for (SearchHit hit : hits) {
                Map<String, Object> sourceAsMap = hit.getSourceAsMap();
                if (sourceAsMap != null && sourceAsMap.containsKey(EsGlobalEnterpriseFields.COMPANY_CITY)) {
                    results.add(sourceAsMap);
                }
            }

            log.info("ES查询完成，有效匹配记录数: {}", results.size());
            return results;

        } catch (Exception e) {
            log.error("执行ES查询失败: {}", e.getMessage(), e);
            return results;
        }
    }

    private List<Map<String, String>> findGlobalEnterprise(GlobalEnterpriseEs globalEnterpriseEs, int offset, int size) {
        BoolQueryBuilder bq = buildWithEmailAndPhoneAndDomain(globalEnterpriseEs);

        return executeEsSearchForIdentifiers(bq, offset, size);

    }

    private BoolQueryBuilder buildWithEmailAndPhoneAndDomain(GlobalEnterpriseEs globalEnterpriseEs) {
        BoolQueryBuilder bq = new BoolQueryBuilder();

        // 邮箱或电话
        if (StringUtils.isNotBlank(globalEnterpriseEs.getBusinessEmail())) {
            bq.must(QueryBuilders.termQuery(EsGlobalEnterpriseFields.BUSINESS_EMAIL, globalEnterpriseEs.getBusinessEmail().toLowerCase()));
        }
//        if (StringUtils.isNotBlank(globalEnterpriseEs.getMobilePhone())) {
//            bq.should(QueryBuilders.termQuery(EsGlobalEnterpriseFields.MOBILE_PHONE, globalEnterpriseEs.getMobilePhone().toLowerCase()));
//        }
        if (StringUtils.isNotBlank(globalEnterpriseEs.getCompanyPhone())) {
            bq.must(QueryBuilders.termQuery(EsGlobalEnterpriseFields.COMPANY_PHONE, globalEnterpriseEs.getCompanyPhone().toLowerCase()));
        }
        if (StringUtils.isNotBlank(globalEnterpriseEs.getCompanyDomain())) {
            bq.must(QueryBuilders.wildcardQuery(
                    EsGlobalEnterpriseFields.COMPANY_DOMAIN,
                    "*" + globalEnterpriseEs.getCompanyDomain().toLowerCase()
            ));
        }
        return bq;
    }

    private List<Map<String, String>> executeEsSearchForIdentifiers(BoolQueryBuilder boolQuery, int offset, int limit) {
        List<Map<String, String>> results = new ArrayList<>();

        try {
            // 创建ES搜索请求
            EsSearchRequest esSearchRequest = new EsSearchRequest();
            esSearchRequest.setBq(boolQuery);
            esSearchRequest.setFrom((long) offset);
            esSearchRequest.setSize((long) limit);
            esSearchRequest.setNeedScroll(false);


            // 只查询必要的字段以提升性能
            String[] fields = {EsGlobalEnterpriseFields.MYSQL_TABLE, EsGlobalEnterpriseFields.MYSQL_ID};
            esSearchRequest.setFields(fields);

            // 执行查询
            SearchResponse searchResponse = EsRestClient.searchWithTermQuery(getEsIndexInfo(), esSearchRequest);

            if (searchResponse == null) {
                log.warn("ES查询返回null响应");
                return results;
            }

            SearchHits searchHits = searchResponse.getHits();
            if (searchHits == null || searchHits.getHits() == null) {
                log.warn("ES查询返回空结果");
                return results;
            }

            SearchHit[] hits = searchHits.getHits();
            log.info("ES查询返回{}条匹配记录", hits.length);

            // 提取标识信息
            for (SearchHit hit : hits) {
                Map<String, Object> sourceAsMap = hit.getSourceAsMap();
                if (sourceAsMap != null) {
                    Map<String, String> identifier = new HashMap<>();
                    identifier.put("mysqlTable", getStringSafely(sourceAsMap, EsGlobalEnterpriseFields.MYSQL_TABLE));
                    identifier.put("id", getStringSafely(sourceAsMap, EsGlobalEnterpriseFields.MYSQL_ID));

                    // 验证标识信息完整性
                    if (identifier.get("mysqlTable") != null && identifier.get("id") != null) {
                        results.add(identifier);
                        log.debug("添加匹配记录: mysqlTable={}, id={}",
                                identifier.get("mysqlTable"), identifier.get("id"));
                    } else {
                        log.warn("跳过不完整的记录: mysqlTable={}, id={}",
                                identifier.get("mysqlTable"), identifier.get("id"));
                    }
                }
            }

            log.info("ES查询完成，有效匹配记录数: {}", results.size());
            return results;

        } catch (Exception e) {
            log.error("执行ES查询失败: {}", e.getMessage(), e);
            return results;
        }

    }

    /**
     * 测试trackTotalHits参数是否生效
     * 用于验证ES计数查询的准确性
     */
    public void testTrackTotalHitsEffectiveness() {
        log.info("🧪 开始测试trackTotalHits参数生效性");

        try {
            // 创建空查询条件，获取全部数据计数
            GlobalEnterpriseEs emptyQuery = new GlobalEnterpriseEs();

            // 测试1: 使用trackTotalHits=true
            EsSearchRequest requestWithTrack = createEsCountRequest(emptyQuery);
            SearchResponse responseWithTrack = EsRestClient.searchWithTermQuery(getEsIndexInfo(), requestWithTrack);

            long countWithTrack = responseWithTrack.getHits().getTotalHits().value;
            String relationWithTrack = responseWithTrack.getHits().getTotalHits().relation.toString();

            log.info("🧪 trackTotalHits=true 结果: count={}, relation={}", countWithTrack, relationWithTrack);

            // 测试2: 使用trackTotalHits=false进行对比
            EsSearchRequest requestWithoutTrack = createEsCountRequest(emptyQuery);
            requestWithoutTrack.setTrackTotalHits(false);
            SearchResponse responseWithoutTrack = EsRestClient.searchWithTermQuery(getEsIndexInfo(), requestWithoutTrack);

            long countWithoutTrack = responseWithoutTrack.getHits().getTotalHits().value;
            String relationWithoutTrack = responseWithoutTrack.getHits().getTotalHits().relation.toString();

            log.info("🧪 trackTotalHits=false 结果: count={}, relation={}", countWithoutTrack, relationWithoutTrack);

            // 分析结果
            if ("EQUAL_TO".equals(relationWithTrack) && !"EQUAL_TO".equals(relationWithoutTrack)) {
                log.info("✅ trackTotalHits参数生效！精确计数功能正常");
            } else if ("EQUAL_TO".equals(relationWithTrack) && "EQUAL_TO".equals(relationWithoutTrack)) {
                log.info("ℹ️ 两种模式都返回精确计数，数据量可能较小");
            } else {
                log.warn("⚠️ trackTotalHits参数可能未生效，需要进一步检查");
            }

        } catch (Exception e) {
            log.error("🧪 trackTotalHits测试失败: {}", e.getMessage(), e);
        }
    }
}